/* 
 * [New BSD License (BSD 3-Clause License)]
 * Copyright (c) 2012, Max Bechtold
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     - Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     - Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     - Neither the name of the Rel2Xml Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package maxbe.rel2xml.generator.dml;

import static maxbe.rel2xml.util.Config.getBoolean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import maxbe.rel2xml.generator.Column;
import maxbe.rel2xml.generator.Column.Mapping;
import maxbe.rel2xml.generator.Table;
import maxbe.rel2xml.grammar.TranslateDmlException;
import maxbe.rel2xml.util.Config;

import org.apache.log4j.Logger;

/**
 * Represents an SQL insert expression
 * 
 * @author Max Bechtold
 * 
 */
public class Insert extends AbstractDmlInstance {

	private Logger log = Logger.getLogger(Insert.class);

	/** The table that is targeted by this insert */
	private Entity target;

	/** List of column-value pairs that are to be inserted */
	private List<Assignment> insertions;

	public Insert(String rootNodePath) {
		this.rootNodePath = rootNodePath;
	}

	public void setTarget(Entity target) {
		this.target = target;
	}

	public void setInsertions(List<ResultColumn> columns, List<String> values) {
		if (columns.size() != values.size()) {
			String msg = ("The number of specified values in query '" + name + "' does not equal the number of columns specified or existant.");
			log.error(msg);
			throw (new TranslateDmlException(msg));
		}

		Iterator<String> it = values.iterator();
		insertions = new ArrayList<Assignment>();

		for (ResultColumn column : columns)
			insertions.add(new Assignment(column, it.next(), null));
	}

	@Override
	public String toXQuery() {
		String insert = super.toXQuery();
		String extVars = declareExtVars();
		if (!extVars.isEmpty())
			insert += extVars + "\n";

		String context = rootNodePath;
		if (target.getTable().getParent() == null)
			context += String.format("/%ss", target.getTable().getName());
		else
			context += String.format("%s%s/%ss", target.getTable().getParent()
					.getXPathSelector(), getInsertPredicate(), target
					.getTable().getName());

		insert += String.format(
				"insert node\n\telement {'%s'} {\n\t\t%s\n\t}\ninto %s;",
				target.getTable().getName(), getContentExpression(), context);

		return insert;
	}

	@Override
	protected String declareExtVars() {
		List<String> variables = new ArrayList<String>();
		String varDecl = super.declareExtVars(variables);

		for (Assignment assignment : insertions) {
			if (assignment.getValue().equals("?")) {
				String var = getVar(assignment.getColumn().getName(), variables);
				assignment.setValue('$' + var);
				varDecl += String.format("declare variable $%s external;\n",
						var);
			}
		}

		return varDecl;
	}

	private String getInsertPredicate() {
		String predicate = "";
		for (Column column : target.getTable().getRefColumns(
				target.getTable().getParent())) {
			if (column.isImplicit()) {
				for (Assignment assignment : insertions) {
					if (assignment.getColumn().getName()
							.equals(column.getName())) {
						if (!predicate.isEmpty())
							predicate += " and ";
						predicate += column.getRefColumn().getXmlName() + " = "
								+ assignment.getValue();
					}

				}
			}
		}
		return (!predicate.isEmpty() ? '[' + predicate + ']' : "");
	}

	private String getContentExpression() {
		String content = "";
		List<Column> unassigned = new ArrayList<Column>(target.getTable()
				.getColumns());

		for (Assignment assignment : insertions) {
			Column column = assignment.getColumn().getColumn();
			unassigned.remove(column);

			String value = assignment.getValue();

			if (column.getMapping() == Mapping.XML_ELEMENT
					|| value.equalsIgnoreCase("null")
					&& getBoolean(Config.OMIT_NULLS) || column.isImplicit()
					&& getBoolean(Config.IMPLICIT_FKEYS))
				continue;

			if (!content.isEmpty())
				content += ",\n\t\t";

			content += String.format("attribute {'%s'} {%s}", column.getName(),
					(value.equalsIgnoreCase("null") ? "" : value));
		}

		if (!getBoolean(Config.OMIT_NULLS)) {
			for (Column column : unassigned) {
				if (column.getMapping() == Mapping.XML_ELEMENT)
					continue;

				unassigned.remove(column);

				if (!content.isEmpty())
					content += ",\n\t\t";

				content += String.format("attribute {'%s'} {''}",
						column.getName(), "");
			}
		}

		for (Assignment assignment : insertions) {
			Column column = assignment.getColumn().getColumn();

			String value = assignment.getValue();

			if (column.getMapping() == Mapping.XML_ATTRIBUTE
					|| value.equalsIgnoreCase("null")
					&& getBoolean(Config.OMIT_NULLS) || column.isImplicit()
					&& getBoolean(Config.IMPLICIT_FKEYS))
				continue;

			if (!content.isEmpty())
				content += ",\n\t\t";

			content += String.format("element {'%s'} {%s}", column.getName(),
					(value.equalsIgnoreCase("null") ? "" : value));
		}

		if (!getBoolean(Config.OMIT_NULLS)) {
			for (Column column : unassigned) {
				if (!content.isEmpty())
					content += ",\n\t\t";

				content += String.format("element {'%s'} {''}",
						column.getName(), "");
			}
		}

		// Add surrounding element for tuples of child tables
		for (Table child : target.getTable().getChildren()) {
			if (!content.isEmpty())
				content += ",\n\t\t";

			content += String.format("<%ss/>", child.getName(), "");
		}

		return content;
	}

	@Override
	public String toSQL() {
		String cols = "";
		for (Assignment assignment : insertions) {
			if (!cols.isEmpty())
				cols += ", ";
			cols += assignment.getColumn().getName();
		}

		String vals = "";
		for (Assignment assignment : insertions) {
			if (!vals.isEmpty())
				vals += ", ";
			vals += assignment.getValue();
		}

		return String.format("insert into %s (%s)\nvalues (%s)", target
				.getTable().getName(), cols, vals);
	}

	@Override
	public String toString() {
		return toSQL();
	}

}
